package com.wzl.spring;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author weiZhiLin
 * @version 1.0
 * @date 2020/1/7 14:14
 */
public class TestDemo {
    public static void testField() {
        UserController userController = new UserController();
        Class<? extends UserController> clazz = userController.getClass();
        Field[] declaredFields = clazz.getDeclaredFields();

        //System.out::print 解释 https://blog.csdn.net/Sky786905664/article/details/80060648
        Arrays.asList(declaredFields).stream().forEach(System.out::println);
    }

    public static void testField2() throws NoSuchFieldException, IllegalAccessException {
        UserController userController = new UserController();
        Class<? extends UserController> clazz = userController.getClass();
        Field field = clazz.getDeclaredField("userService");
        // 报错私有属性禁止访问，私有属性编译后会写入文件中
        field.set(userController, new UserService());
    }

    public static void testField3() throws NoSuchFieldException, IllegalAccessException {
        UserController userController = new UserController();
        Class<? extends UserController> clazz = userController.getClass();
        Field field = clazz.getDeclaredField("userService");

        // 障眼法 OxO
        field.setAccessible(true);
        field.set(userController, new UserService());
        System.out.println(userController.getService());
    }

    // 核心代码 ლ(´ڡ`ლ)
    public static void testField4() throws Exception {
        UserController userController = new UserController();
        Class<? extends UserController> clazz = userController.getClass();
        Field field = clazz.getDeclaredField("userService");

        String name = field.getName();
        // 驼峰命名
        name = "set"+name.substring(0, 1).toUpperCase() + name.substring(1, name.length());
        System.out.println(name);

        Method method = clazz.getMethod(name, UserService.class);
        method.invoke(userController, new UserService());
        System.out.println(userController.getService());
    }
   /* public static void main(String[] args) throws Exception {
//        testField();
//        testField2();
//        testField3();
        testField4();
    }*/
}
